import React, { forwardRef, useImperativeHandle, useState, useEffect } from 'react';

import {
  Button,
  DatePicker,
  Form,
  Input,
  Modal,
  Radio,
  Tag,
  Select,
  InputNumber,
  message,
  Row,
  Col,
  Tree,
} from 'antd';
import { modalLayoutLg, modalLayoutSm } from '@/config/layout';
import { request } from 'umi';
const DasCapitalReportModal = (props: any, refs: any) => {
  const [form] = Form.useForm();
  const [treedata, settreedata] = useState([]);
  // const [fileList,setfileList] = useState([]);
  const [measureClassData, setmeasureClassData] = useState([]);
  const [lselect, setlselect] = useState({});
  const { setFieldsValue, resetFields } = form;
  const [code, setCode] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [menuTypeList, setMenuTypeList] = useState([]);
  //查询银行列表
  const getMenuTypeList = () => {
    request('/sys/dict/getDictListByType', {
      method: 'POST',
      data: { type: 'menu_type' },
    }).then((res) => {
      let list = res?.data || [];
      list.map((e, i) => {
        list[i]['name'] = e['label'];
        list[i]['key'] = e['value'];
      });
      setMenuTypeList(list);
    });
  };
  //页面加载初始化
  useEffect(() => {
    getMenuTypeList();
  }, []);
  const getTreeData = async () => {
    request('/sys/menu/list', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {},
    }).then((response) => {
      let menusnewdata = response?.data || [];
      menusnewdata = [{ name: '功能菜单', id: '1' }].concat(menusnewdata);
      settreedata(menusnewdata);
    });
  };
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };

  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setCode('');
    resetFields();
    props.callback && props.callback();
  };
  //确定
  const handleOk = () => {
    form
      .validateFields()
      .then((vals) => {
        let Obj = form.getFieldsValue();
        console.log(Obj);
        Obj = {
          ...Obj,
        };

        const url = code ? '/sys/menu/save' : '/sys/menu/save';
        if (code) {
          Obj.id = code;
        } else {
        }
        Obj['parent'] = {
          id: Obj.parentId,
        };
        request(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          data: Obj,
        }).then((res) => {
          message.success(res?.meta?.msg);
          setIsModalVisible(false);
          handleCancel();
        });
      })
      .catch((info) => { });
  };

  const getDetail = (id: any) => {
    request('/sys/menu/form', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
        id,
      },
    }).then((res) => {
      setFieldsValue(res?.data);
      showModal();
    });
  };
  useImperativeHandle(refs, () => ({
    init: (record: any) => {
      getTreeData();
      if (record) {
        setFieldsValue({
          parentName: record.name,
          parentId: record.id,
        });
      } else {
        setFieldsValue({
          parentName: '功能菜单',
          parentId: '1',
        });
      }
      showModal();
      // setfileList([]);
    },

    getForm: (id: any, record: any) => {
      if (id) {
        setCode(id);
        getDetail(id);
      } else {
        resetFields();
        showModal();
      }
    },
  }));

  return (
    <>
      <Modal
        title={code === '' ? '新增' : '编辑'}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        centered
        width={700}
        maskClosable={false}
        bodyStyle={{
          maxHeight: window.innerHeight - 150,
          overflowY: 'auto',
        }}
      >
        <Form form={form} layout="vertical" {...modalLayoutSm}>
          <Row>
            <Form.Item name="parentIds" style={{ display: 'none' }}>
              <Input disabled />
            </Form.Item>
            <Form.Item label="上级菜单" name="parentId" style={{ display: 'none' }}>
              <Input disabled />
            </Form.Item>
            <Col span={12}>
              <Form.Item
                label="上级菜单"
                name="parentName"
                onClick={() => {
                  Modal.info({
                    okText: '确定',
                    title: '选择菜单',
                    content: (
                      <div>
                        <Tree
                          treeData={treedata}
                          onSelect={(selectedKeys, e) => {
                            console.log(e.node);
                            setlselect(e.node);
                          }}
                          fieldNames={{
                            title: 'name',
                            key: 'id',
                          }}
                        ></Tree>
                      </div>
                    ),
                    onOk() {
                      setFieldsValue({
                        parentName: lselect?.name,
                        parentId: lselect?.id,
                      });
                    },
                  });
                }}
              >
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="名称"
                name="name"
                rules={[{ required: true, message: '请输入名称' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="链接"
                name="href"
                extra="点击菜单跳转的页面，二级菜单必须维护为PageView，三级菜单维护为前端路由"
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="目标" name="target" extra="链接地址打开的目标窗口，默认：mainFrame">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="排序" name="sort" extra="排列顺序，升序。">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="可见" name="isShow" extra="该菜单或操作是否显示到系统菜单中">
                <Radio.Group>
                  <Radio value="1">可见</Radio>
                  <Radio value="0">隐藏</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="权限标识"
                name="permission"
                extra='控制器中定义的权限标识，如：@RequiresPermissions("权限标识")'
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="菜单类型" name="menuType">
                <Select placeholder="请选择">
                  {menuTypeList.map((item, i) => {
                    return (
                      <Select.Option key={item.key} title={item.name} value={item.key}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="备注" name="remarks">
                <Input.TextArea />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </>
  );
};
const AddMCom = forwardRef(DasCapitalReportModal);

export default AddMCom;
